<template>
	<!-- 应用.main类 -->
	<view class="main" @touchstart.stop>
		<view class="closeicon" @click="handleClose"><uni-icons type="close" size="20"></uni-icons></view>

		<view class="user" v-if="userInfo">
			<view class="userpic">
				<image class="nicimg" :src="userInfo.nicPic.url" mode="aspectFill"></image>
			</view>
			<view class="name">
				<view class="user-name">
					<text style="font-size: 28rpx; color: #ccc">呢 称：</text>
					<text style="font-size: 32rpx">{{ userInfo.nicName }}</text>
				</view>
				<view class="user-id">
					<text style="font-size: 28rpx; color: #ccc">邻里id：</text>
					<text style="font-size: 28rpx">{{ userInfo.userId }}</text>
				</view>
			</view>
		</view>
		<view class="" v-if="msgList.length === 0"><text style="font-size: 28rpx; color: #ccc">该用户24小时内没有发布信息</text></view>
		<view class="detail" style="padding: 10rpx 10rpx" v-if="msgList.length > 0">
			<text style="color: #55aaff; font-size: 32rpx">近24小时发布的信息内容：</text>
			<view class="chatarea">
				<scroll-view scroll-y="true" class="msgs" ref="msgs" scroll-with-animation="true" :scroll-into-view="viewId">
					<view v-for="(item, index) in msgList" :key="index" :id="`msgall-${item.timestamp}`" style="position: relative" @longpress.stop="showMenu(item.timestamp)">
						<view class="timeformat" style="display: flex; flex-direction: row" v-if="isShowTime(index)">
							<view class="">
								<text style="font-size: 24rpx; color: #55aa00">{{ formatMessageTime(item.timestamp) }}</text>
							</view>
							<view v-if="formatDistance(item)" class="">
								<text style="font-size: 24rpx; color: #55aa00">{{ formatDistance(item) }}</text>
							</view>
							<view v-else class="">
								<text style="font-size: 24rpx; color: #55aa00">定位中....</text>
							</view>
						</view>
						<view class="msg" v-if="item.messageType === 2" style="padding: 10rpx 10rpx">
							<text class="content-text" :style="{ 'font-size': '30rpx' }">{{ item.content.text }}</text>
						</view>
						<!-- 语音信息 -->
						<view class="msg" style="display: flex; flex-direction: row; align-items: center" v-if="item.messageType === 1" :id="`msg-${item.timestamp}`">
							<view class="progress-bar" :style="{ width: (item.content.duration < 6 ? 100 : item.content.duration * 10) + 'rpx' }" @click.stop="handonPlay(item)">
								{{ currentMsg === item.timestamp ? progressPercent.toFixed(0) + '%' : item.content.duration + '秒' }}
								<view v-if="currentMsg === item.timestamp" class="progress" :style="{ width: progressPercent + '%' }"></view>
							</view>
							<view class=""><uni-icons type="sound" size="30" color="#ffaf69"></uni-icons></view>
						</view>

						<view class="msg" v-else-if="item.messageType === 3" @click="handerPicShow(index)">
							<view class="" v-for="(pic, index) in item.content.mediaPath" :key="index">
								<image :src="pic.url" mode="aspectFit"></image>
							</view>
						</view>
						<view class="msg video" v-else-if="item.messageType === 6" @click="handlevideoPath(item)">
							<image class="video_v" :src="item.content.videoPath.videoPic.tempFileURL" mode="aspectFill"></image>

							<uni-icons type="videocam-filled" class="video-cam" size="40" color="#fff"></uni-icons>
						</view>
						<view v-if="timeStamp === item.timestamp" @click="delmsg" class="delmenu"><text style="color: white; font-size: 28rpx">删除记录</text></view>
					</view>
				</scroll-view>
			</view>
		</view>

		<view class="btn">
			<view class="nicpic">
				<image class="images" mode="aspectFit" :src="isFriend ? '/static/loved.png' : '/static/love.png'" alt="关注" @click="handerAdd"></image>
			</view>
			<view class="nicpic" @click="handerTel(userInfo.userTel)">
				<image class="images" mode="aspectFit" src="/static/tele.png" alt="关注1"></image>
			</view>
			<view class="nicpic" style="background-color: green" @click="handerTarget">
				<text style="font-size: 30rpx; color: white; font-weight: 700">私聊</text>
			</view>
		</view>
		<videoPlay :videoInfo="videoInfo" @closeVideo="closeVideo"></videoPlay>
		<addFriend :isAddFriend='isAddFriend' v-if="isAddFriend" :userInfo="userInfo"></addFriend>
	</view>
</template>
<script>
const db = uniCloud.databaseForJQL();
import formatMessageTime from '../utils/formatMessageTime.js';
import { formatDistance } from '../utils/distance.js';
import { play } from '../methods/play';
import videoPlay from '../components/videoPlay.vue';
import { VoicePlayer } from '../utils/VoicePlayer';
import addFriend from '../components/addFriend.vue'
export default {
	name: 'markerInfo',
	components: {
		videoPlay,
		addFriend
	},
	props: {
		markerId: {
			type: String,
			required: true
		},
		
	},
	
	data() {
		return {
			stateConfig: {
				isPlaying: false,
				isplay: -1
			},
			viewId: '',
			isAdd: false,
			userInfo: null,
			isplay: -1,
			videoInfo: {},
			msgList: [],
			timeStamp: 0,
			currentMsg: -1,
			selectedIndex: -1,
			progressPercent: 0
		};
	},
	computed: {
		storeData() {
			return this.$store.state.msg;
		},
	isFriend() {
	
	  const friends = this.storeData?.user?.friends;
	  return Array.isArray(friends) ? friends.includes(this.markerId) : false;
	}
		
	},

	async mounted() {
		this.msgList = this.storeData.publicMessageList.filter((item) => item.sendUserId === this.markerId);
		console.log('222', this.msgList);

		this.userInfo = await this.getMarkerInfo(this.markerId);
				uni.$on('progressPercent',  persent=>{
					this.progressPercent=persent
				})
	},
    destroyed() {
    	uni.$off('progressPercent')
    },
	methods: {
		formatMessageTime,
		isShowTime(index) {
			if (index === 0) {
				return true;
			} else {
				return this.msgList[index].timestamp - this.msgList[index - 1].timestamp > 300000;
			}
		},
		formatDistance(item) {
			return formatDistance(this.storeData.location, item);
		},
		showMenu(timestamp) {
			if (app.user.userId === this.userId) {
				this.timeStamp = timestamp;
			}
		},
		voiceWight(times) {
			if (times < 2) {
				return 200;
			} else if (times > 60) {
				return 500;
			} else {
				return times * 10 + 200;
			}
		},
		handonPlay(msg) {
			// 先停止当前播放
			if (this.currentMsg !== -1 && this.currentMsg !== msg.timestamp) {
				VoicePlayer.stop();
				this.onPlay = false;
				this.isPlaying = false;
			}
             this.currentMsg=msg.timestamp
			// 查找当前消息在列表中的索引
			const index = this.msgList.findIndex((item) => item.timestamp === msg.timestamp);

			if (index === -1) {
				console.warn('未找到对应的消息');
				return;
			}

			// 切换播放状态
			this.onPlay = !this.onPlay;

			if (!this.onPlay) {
				this.isPlaying = false;
				VoicePlayer.stop();
			} else {
				this.isPlaying = true;
				VoicePlayer.play(this, index);
			}
		},
		async delmsg() {
			try {
				const a = await db
					.collection('message_public')
					.where({
						sendUserId: this.userId,
						timestamp: this.timeStamp
					})
					.remove();
				this.msgList = this.msgList.filter((item) => item.timestamp !== this.timeStamp);
			} catch (e) {
				console.error(e);
			}
		},
		async getMarkerInfo(userId) {
			try {
				const result = await db
					.collection('linli-user')
					.where({
						userId: userId
					})
					.get();

				if (result.data.length > 0) {
					return result.data[0];
				}
			} catch (e) {
				return {};
			}
		},
		handerAdd() {
			console.log(this.storeData.user,this.userInfo);
			if(!this.isFriend){
			this.isAddFriend=true//打开好友添加页
			console.log(this.isAddFriend);	
			};
		},
		handerPicShow(i) {
			uni.previewImage({
				urls: [this.msgList[i].content.mediaPath],
				longPressActions: {
					itemList: ['发送给朋友', '保存图片', '收藏'],
					success: function (data) {
						console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
					},
					fail: function (err) {
						console.log(err.errMsg);
					}
				}
			});
		},
		handleClose() {
			this.$emit('close');
		},
		handerTarget() {
			uni.navigateTo({
				url: `/pages/PrivateChat/PrivateChat?id=${this.userInfo.userId}`
			});
		},
		async handlevideoPath(item) {
			console.log(item);
			this.videoInfo = item;
		},
		closeVideo() {
			this.videoInfo = {};
		},
		handerTel(tel) {
			uni.makePhoneCall({
				phoneNumber: tel
			});
		}
	}
};
</script>
<style lang="scss" scoped>
/* 通用样式需在nvue中使用flex布局 */

.main {
	position: fixed;
	top: 200rpx;
	left: 75rpx;
	width: 600rpx;
	padding: 22rpx;
	background-color: #ffffff;
	border-radius: 32rpx;
	z-index: 999;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}
.detail {
	width: 600rpx;
}

.user {
	display: flex;
	flex-direction: row;
	align-items: center;
	height: 150rpx;
	margin-bottom: 24rpx;
}
.video_v {
	width: 250rpx;
	height: 300rpx;
}
.video {
	position: relative;
	margin-top: 25rpx;
}
.video-cam {
	position: absolute;
	top: 125rpx;
	left: 100rpx;
}
.closeicon {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	width: 50rpx;
	height: 50rpx;
}
.msgs {
	height: 600rpx;
	width: 550rpx;
	padding: 15rpx 15rpx;
}

.userpic {
	width: 120rpx;
	height: 120rpx;
	border-radius: 50%;
	margin-right: 32rpx;
}
.nicimg {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
}

.images {
	width: 100%;
	height: 100%;
}

.name {
	flex-direction: column;
	justify-content: center;
}

.user-name {
	display: flex;
	flex-direction: row;
	font-size: 36rpx;
	font-weight: 600;
	color: #333333;
	margin-bottom: 8rpx;
}

.user-id {
	display: flex;
	flex-direction: row;
	font-size: 36rpx;
	font-weight: 600;
	color: #333333;
	margin-bottom: 8rpx;
}
.progress-bar {
	display: flex;
	justify-content: center;
	height: 60rpx;
	border-radius: 10rpx;
	flex-direction: column;
	background-color: #ffaa00;
	align-items: center;
	font-size: 28rpx;
	color: #007bff;
	padding: 0;
	overflow: hidden;
}
.progress {
	align-self: self-start;
	background-color: #55ffff;
	height: 10rpx;
}

.btn {
	display: flex;
	flex-direction: row;
	justify-content: space-around;
	height: 100rpx;
	border-radius: 50rpx;
	padding-left: 20rpx;
	padding-right: 20rpx;
	align-items: center;
	background-color: aqua;
}

.nicpic {
	display: flex;
	flex-direction: column;
	height: 80rpx;
	width: 80rpx;
	background-color: rgba(255, 255, 255, 0.8);
	box-shadow: 2rpx 2rpx 2rpx 1rpx rgba(0, 0, 0, 0.2);
	border-radius: 40rpx;
	align-items: center;
	justify-content: center;
}

.images {
	width: 60rpx;
	height: 60rpx;
}
.delmenu {
	background-color: #333333;
	width: 120rpx;
	height: 46rpx;
	border-radius: 10rpx;
	position: absolute;
	right: 0;
	top: 0;
}
</style>
